package com.lolineet.auth.provider;

import com.lolineet.auth.token.SysUsernamePasswordAuthToken;
import com.lolineet.auth.entity.SysUsernamePasswordLoginEntity;
import com.lolineet.exception.BusinessException;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.List;

import static com.lolineet.result.ResultCode.USERNAME_OR_PASSWORD_ERROR;

/**
 * UsernamePasswordAuthProvider
 *
 * @author YUKI.N
 * @version 1.0
 * @description
 * @date 2025/4/17 17:25
 */
@Component
public class SysUsernamePasswordAuthProvider implements AuthenticationProvider {
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        SysUsernamePasswordLoginEntity loginEntity = (SysUsernamePasswordLoginEntity) authentication.getPrincipal();
        String password = (String) authentication.getCredentials();
        // 示例逻辑，实际中应使用 userService + 密码加密判断
        if ("admin".equals(loginEntity.getUsername()) && "123456".equals(password)) {
            return new SysUsernamePasswordAuthToken(List.of(new SimpleGrantedAuthority("ROLE_USER")),loginEntity,password);
        }
        /*TODO 登录逻辑*/
        throw new BusinessException(USERNAME_OR_PASSWORD_ERROR);
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return SysUsernamePasswordAuthToken.class.isAssignableFrom(authentication);
    }
}
